<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
// 导入数据处理文件，将数据名称改变成英文
import { getImportJsData } from '@/utils/excel'
import { fetchImportExcel } from '@/api/employees'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      // file excel文件对象
      // 判断文件大小
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      // 函数内部必须要返回true或者false，当返回false时，解析逻辑将不会被执行
      return false
    },
    // results: 对象数组 表体数据
    // header: 数组 表体数据
    async  handleSuccess({ results, header }) {
      const headerRelation = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName'
      }
      // 将中文表头改变成英文格式
      const result = getImportJsData(results, headerRelation)

      // 调用接口导入数据
      await fetchImportExcel(result)
      // 提示用户添加成功
      this.$message.success('导入成功')
      // 跳转回员工列表界面
      this.$router.back()
      this.tableData = results
      this.tableHeader = header
    }
  }
}
</script>
